#include "pch.h"
#include "GRTXRenderer.h"
#include <GGiThreadPool.h>
#include "GRTXScene.h"
#include "GRTXRay.h"

void  GRTXRenderer::Render(std::vector<GMath::Vector3>& frameBuffer,size_t& process,const GRTXScene& scene, int spp)
{
	frameBuffer.clear();
	frameBuffer.resize(scene.Width * scene.Height );

	std::atomic_size_t finishTask = 0;
	size_t m = -1;
	{
		GGiThreadPool pool;
		pool.start();
		for (int i = 0; i < scene.Height; i++)
		{
			for (int j = 0; j < scene.Width; j++)
			{
				auto ray = scene.GenRay((j * 1.0f) / scene.Width, (i * 1.0f) / scene.Height);
				m++;
				auto Func = [&frameBuffer,&scene,spp,m,ray,&process,&finishTask]() {

					GMath::Vector3 color;
					for (int k = 0; k < spp; k++)
					{
						color += scene.CastRay(ray);
					}
					color = color / spp;

					frameBuffer[m] = color;

					finishTask++;
					process = finishTask;
				};
				if (0)
				{
					Func();
				}else
					pool.appendTask(Func);
			}
		}
		pool.stop();
	}
}

GRTXRenderer& GRTXRenderer::Get()
{
	static GUPtr<GRTXRenderer> instance(new GRTXRenderer());
	return *instance.get();
}
